<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
      <el-form-item label="输入搜索" prop="name">
        <el-input v-model="queryParams.bucketName" placeholder="垃圾站名称" clearable style="width: 300px;" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
      </el-form-item>
      <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleView()" class="manage-add-btn">添加垃圾站</el-button>
    </el-form>
    <el-table ref="tables" v-loading="loading" :data="list" v-if="!loading">
      <el-table-column label="垃圾站编号" align="center" prop="bucketNumber" />
      <el-table-column label="垃圾站名称" align="center" prop="name" />
      <el-table-column label="垃圾站号码" align="center" prop="deviceNumber" />
      <el-table-column label="垃圾站分类" align="center" prop="type">
        <template>
          <div>垃圾站</div>
        </template>
      </el-table-column>
      <el-table-column label="最大容量(m³)" align="center" prop="capacity" />
      <el-table-column label="预警值(%)" align="center" prop="thresholdValue" />
      <el-table-column label="已用容量(%)" align="center" prop="threshold">
        <template slot-scope="{ row }">
          <div>{{ row.threshold || 0 }}</div>
        </template>
      </el-table-column>
      <el-table-column label="定位位置" align="center">
        <template slot-scope="{ row }">
          <div>{{ row.locationName }}</div>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="{ row }">
          <div v-if="row.status == 0">已启用</div>
          <div v-else style="color: red">已停用</div>
        </template>
      </el-table-column>
      <el-table-column label="预警状态" align="center">
        <template slot-scope="{ row }">
          <div v-if="row.maxStatus == 1" style="color: rgb(255, 94, 0)">满溢预警</div>
          <div v-else-if="row.maxStatus == 2" style="color: red">超出容量</div>
          <div v-else>--</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleView(scope.row)">修改</el-button>
          <el-button v-if="scope.row.status == 0" size="mini" type="text" @click="handleChange(scope.row.id)">停用</el-button>
          <el-button v-else size="mini" type="text" @click="handleChange(scope.row.id)">启用</el-button>
          <el-button size="mini" type="text" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!-- 操作日志详细 -->
    <el-dialog :title=title :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" label-width="150px" size="mini" :rules="rules">
        <el-form-item label="垃圾站名称：" prop="name" style="width: 60%;">
          <el-input v-model="form.name" type="text" placeholder="请输入垃圾站名称"></el-input>
        </el-form-item>
        <el-form-item label="垃圾站编号：" prop="bucketNumber" style="width: 60%;">
          <el-input v-model="form.bucketNumber" placeholder="请输入垃圾站编号"></el-input>
        </el-form-item>
        <el-form-item label="定位位置：" prop="memlocationber" style="width: 60%;">
          <el-input v-model="formlocationName" placeholder="请选择定位位置" suffix-icon="el-icon-location" readonly
            @focus="initMap()"></el-input>
        </el-form-item>
        <!-- <el-form-item label="垃圾站分类：" style="width: 60%;">
          <el-select placeholder="请选择垃圾站分类" v-model="form.type" clearable filterable>
            <el-option v-for="(m, index) in classifyList" :key="index" :label="m.name" :value="m.type"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="最大容量(m³)：" style="width: 60%;">
          <el-input v-model="form.capacity" type="tel" placeholder="请输入最大容量"></el-input>
        </el-form-item>
        <el-form-item label="预警值(%)：" style="width: 60%;">
          <el-input v-model="form.thresholdValue" type="tel" placeholder="请输入预警值"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit()" style="width: 20%;">提 交</el-button>
      </div>
    </el-dialog>
    <el-dialog title="选择定位" :visible.sync="openMap" width="70%" append-to-body>
      <div id="map" style="width: 100%; height: 70vh;"></div>
    </el-dialog>
  </div>
</template>

<script>
import { bucketList, addbucket, editbucket, delbucket, changebucket } from "@/api/system/resource";
import { getLocationName } from '@/utils/map'

export default {
  name: "Operlog",
  data() {
    return {
      rules: {
        name: [
          { required: true, message: '请填写名称', trigger: 'blur' },
        ],
        num: [
          { required: true, message: '请填写编号', trigger: 'blur' },
        ],
      },
      title: '添加垃圾站',
      editId: null,
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      // 表单参数
      form: { bucketNumber: '', name: '', type: 2, areaLocation: {}, capacity: '', thresholdValue: "" },
      formlocationName: '',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bucketName: undefined,
        type: 2
      },
      open: false,
      openMap: false,
      map: null,
      marker: null,
      center: [116.122046, 24.288832],
    };
  },

  created() {
    this.getList();
  },
  methods: {
    /** 查询登录日志 */
    async getList() {
      this.loading = true;
      const res = await bucketList(this.queryParams);
      if (res.code === 200) {
        this.list = res.data.records;
        for (const item of this.list) {
          if (item.jsonString) {
            const jsonObj = JSON.parse(item.jsonString);
            const lnglat = { lng: jsonObj.longitude, lat: jsonObj.latitude };
            item.locationName = await getLocationName(lnglat);
          }
        }
        this.total = res.data.total;
        this.loading = false;
        return;
      }
      this.$modal.msgSuccess(res.msg);
    },
    // 修改 — 使用深拷贝切断与表格行的引用，避免编辑时表格数据同步变化
    handleView(row) {
      this.open = true;
      if (row) {
        this.editId = row.id;
        this.title = '修改垃圾站';

        // 深拷贝 row 到表单，切断引用
        this.form = JSON.parse(JSON.stringify(row));

        // 强制设置类型（保持原逻辑）
        this.form.type = 2;

        // 文本显示的定位名从 row 或拷贝后的 form 中取
        this.formlocationName = row.locationName || this.form.locationName || '';
      } else {
        this.editId = null;
        this.form = { bucketNumber: '', name: '', type: 2, areaLocation: {}, capacity: '', thresholdValue: "" };
        this.formlocationName = '';
      }
    },
    //删除区域
    handleDelete(id) {
      this.$confirm('此操作将删除该区域, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delbucket(id).then(response => {
          if (response.code === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          }
          this.getList();
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //停用
    handleChange(id) {
      changebucket(id).then(response => {
        if (response.code === 200) {
          this.$message({
            type: 'success',
            message: response.msg
          });
        }
        this.getList();
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    submit() {
      if (this.editId) {
        this.form.id = this.editId;
        editbucket(this.form).then(response => {
          if (response.code === 200) {
            this.open = false;
            this.$modal.msgSuccess("修改成功");
            this.getList();
            return;
          }
          this.$modal.msgSuccess(response.msg);
        });
      }
      else {
        addbucket(this.form).then(response => {
          if (response.code === 200) {
            this.open = false;
            this.$modal.msgSuccess("新增成功");
            this.getList();
            return;
          }
          this.$modal.msgSuccess(response.msg);
        });
      }

    },
    initMap() {
      this.openMap = true;
      return new Promise((resolve, reject) => {
        const script = document.createElement('script');
        const apiKey = process.env.VUE_APP_webapiKey;
        script.src = `https://webapi.amap.com/maps?v=2.0&key=${apiKey}&plugin=AMap.Geocoder`;
        script.async = true;

        script.onload = () => {
          try {
            this.map = new AMap.Map('map', {
              zoom: 12,
              center: this.center
            });
            // 添加点击事件
            this.map.on('click', (e) => {
              this.placeMarker(e.lnglat);
            });
            resolve(); // 完成时调用 resolve
          } catch (error) {
            reject(error); // 如果出错，调用 reject
          }
        };

        script.onerror = () => {
          reject(new Error("地图脚本加载失败")); // 加载失败时调用 reject
        };

        document.head.appendChild(script);
      });
    },
    async placeMarker(lnglat) {
      if (this.marker) {
        this.marker.setMap(null);
      }
      this.marker = new AMap.Marker({
        position: lnglat,
        map: this.map
      });
      this.formlocationName = await getLocationName(lnglat);
      this.form.areaLocation = { latitude: lnglat.lat, longitude: lnglat.lng }
      this.openMap = false;
    },
  },

};
</script>
<style lang="scss" scoped>
.manage-add-btn {
  float: right;
}

.dialog-footer {
  text-align: center;
}
</style>
